'use strict';

var mongoose = require('mongoose');
var fs = require('fs');
var path = require('path');
var config = require('./config');
var models_path = path.join(config.root, 'models');

// 加载model文件
fs.readdirSync(models_path).forEach(function(file) {
    if (~file.indexOf('.js')) require(path.join(models_path ,file));
});

module.exports = function(){
    var connects = {};


    var createConnection = function(tenant){
        var dbconf = config.db[tenant];
        var db = mongoose.createConnection(dbconf.url, dbconf.options);
        
        db.on('error', function(err) {
            console.error(err);
        });
        
        // Reconnect when closed
        db.on('disconnected', function() {
            db.connect(dbconf.url, dbconf.options);
        });

        connects.tenant = db;

        return db;
    };

    var initModel = function(connect){
        for(var key in global.models) {
            connect.model(key, global.models[key]);
        }
    };

    var model = function(tenant, modelName){
        var connect = connects.tenant;

        if (!connect) {
            connect = createConnection(tenant);
            initModel(connect);
        }

        return connect.model(modelName);
    };

    var models = function(modelName){
        var models = [];

        if (_.isEmpty(connects)) {
            initModel(createConnection('atwork'));
        }
       
        for (var key in connects) {
            models.push(connects[key].model(modelName));
        }

        return models;
    };

    return {
        model : model,
        models : models
    };
}();
